/**
 * 企业报表数据列表Mixin
 * @mixin
 */
import { uuid } from '@/utils'
import TdButton from '@/components/td-button/index.vue'
import {
  // COMPANY_PRODUCT_LIST,
  // DETAILED_LIST_OF_COMPANY_INDICATORS,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID, ENTERPRISE_BASIC_INFORMATION_TABLE_NAME,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
  TABLE_ACCOUNT_CONFIGS,
  TABLE_FIELD_QUARTER,
  TABLE_FIELD_YEAR,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
  TABLE_REPORTED,
  TABLE_RESOLVED
} from '@/config'
import { loadReportingSituation } from '@/api/enterpriseQuarterlyReport'
import { loadDicCodeByDictionaryEncoList } from '@/api/sysDictionaryEnco'

export default {
  components: { TdButton },
  data () {
    return {
      loading: false,
      lists: [],
      columns: [
        {
          label: '表名',
          prop: 'alias',
          width: 120,
        },
        {
          label: '表全称',
          prop: 'name'
        },
        {
          label: '表状态',
          prop: 'statusText'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    userInfo () {
      return this.$store.state.user.userInfo || {}
    },
    enterpriseId () {
      const { tenantId } = this.userInfo
      return tenantId ? String(tenantId) : null
    },
    enterpriseName () {
      const { tenantName, userName } = this.userInfo
      return tenantName || userName || ''
    },
  },
  async mounted () {
    await this.queryLists()
  },
  methods: {
    getTableName (tableAccountId) {
      // 企业基本情况表
      if (Number(tableAccountId) === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
        return ENTERPRISE_BASIC_INFORMATION_TABLE_NAME
      }
      let value, target
      for (const key in TABLE_ACCOUNT_CONFIGS) {
        value = TABLE_ACCOUNT_CONFIGS[key]
        if (value.ID === Number(tableAccountId)) {
          target = value
        }
      }
      if (target) {
        return target.NAME
      }
      return ''
    },
    queryLists () {
      this.loading = true
      const params = {
        [TABLE_FIELD_YEAR]: this.year,
        [TABLE_FIELD_QUARTER]: this.quarter,
      }
      return loadReportingSituation(params).then(res => {
        res.data = res.data || []
        /**
         * Iterator
         * @param v{{
         *   id?: string;
         *   state?: string;
         *   stateName?: string;
         *   illustrate?: string;
         * }}
         * @returns {{statusText: *, name: (string|*|string), remark: (string|*), id: *, tableAccountId: number, status: string}}
         */
        const mapFn = (v, i) => ({
          id: uuid(),
          name: this.getTableName(v.id),
          alias: [
            '季报表1-2',
            '季报表1-2-1',
            '季报表1-3',
          ][i],
          tableAccountId: Number(v.id),
          status: String(v.state),
          statusText: v.stateName,
          remark: v.illustrate
        })

        const targetTIds = [
          // COMPANY_PRODUCT_LIST.ID,
          // DETAILED_LIST_OF_COMPANY_INDICATORS.ID,
          ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
          ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
          TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID,
        ]
        const data = res.data.filter(v => targetTIds.includes(+v.id))
        this.lists = targetTIds.map((tId, i) => {
          const target = data.find(v => +v.id === +tId)
          return mapFn(target, i)
        })
      }).finally(() => {
        this.loading = false
      })
    },
    rowStyle ({ row }) {
      const status = Number(row.status)
      if (status === 4) {
        return { background: 'rgba(103, 194, 58, .2)' }
      }
      if (status === 5) {
        return { background: 'rgba(245, 108, 108, .2)' }
      }
      if (status === 1) {
        return { background: 'rgba(192, 196, 204, .1)' }
      }
      return {}
    },
    findTable (id) {
      const tables = Object.keys(TABLE_ACCOUNT_CONFIGS)
      const key = tables.find(key => TABLE_ACCOUNT_CONFIGS[key].ID === Number(id))
      return key ? TABLE_ACCOUNT_CONFIGS[key] : null
    },
    async edit (row) {
      const tableAccountId = row.tableAccountId

      // 企业基础情况表
      if (tableAccountId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
        this.tableAccountId = ENTERPRISE_BASIC_INFORMATION_TABLE_ID
        this.tableName = ENTERPRISE_BASIC_INFORMATION_TABLE_NAME
        this.tableColumns = []
        this.tableStatus = ''
        // 企业报表已上报或已通过只有查看功能
        this.readonly = String(row.status) === TABLE_RESOLVED || String(row.status) === TABLE_REPORTED
        this.$nextTick(() => {
          this.showTableAccount = true
        })
        return
      }

      const TABLE_ACCOUNT = this.findTable(tableAccountId)
      if (TABLE_ACCOUNT === null) {
        return false
      }
      this.tableAccountId = Number(tableAccountId)
      this.tableName = TABLE_ACCOUNT.NAME
      this.tableColumns = TABLE_ACCOUNT.COLUMNS
      this.tableStatus = row.status
      // 企业报表已上报或已通过只有查看功能
      this.readonly = String(row.status) === TABLE_RESOLVED || String(row.status) === TABLE_REPORTED

      // 进度节能目标完成情况表 动态的"五年"
      if (tableAccountId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
        const five = await loadDicCodeByDictionaryEncoList('WU_NIAN_JI_HUA')
          .then(({ data }) => {
            if (Array.isArray(data)) {
              return {
                oneYear: data[0].dicValue,
                twoYear: data[1].dicValue,
                threeYear: data[2].dicValue,
                fourYear: data[3].dicValue,
                fiveYear: data[4].dicValue,
              }
            }
            return {
              oneYear: '2025年',
              twoYear: '2025至2026年',
              threeYear: '2025至2027年',
              fourYear: '2025至2028年',
              fiveYear: '2025至2029年',
            }
          })

        const cols = [...this.tableColumns]
        Object.keys(five).forEach(key => {
          const target = cols.find(col => col.prop === key)
          if (target) {
            target.label = five[key]
          }
        })

        this.tableColumns = cols
      }

      this.$nextTick(() => {
        this.showTableAccount = true
      })
    },
  },
}
